package cc.ufinity.networkdiagnose.widget;

import java.text.DecimalFormat;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.ChinaUnicomAccount;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.UnicomWebAuthManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;

public class WebauthUnicomTestWidgetProxy extends GeneralTestWidget {

    private Activity ctx;
    private Handler handlerChild;
    private final Handler handler;
    private UnicomWebAuthManager webAuthManager;
    private WlanManager wlanManager;
    private int frequency;
    private int current;
    private String defaultUrl;
    private boolean processing;
    private float loginTotalTime;
    private int lsuccessTimes;
    private int osuccessTimes;
    private float logoutTotalTime;
    private static String TAG = "WebauthTestWidget";
    private int testedTimes;
    private static String username;
    private static String password; 
    private static String address; 
    private Task task;
    public static int testFlag = 0; 
    public static int taskFlag = 0; 
	private boolean isFirst = true;
	private boolean logouting = false;

    public WebauthUnicomTestWidgetProxy(Activity context, Handler handl) {
        super(context);
        this.ctx = context;
        this.handlerChild = handl;
//        inflate(context, R.layout.webauth_test_widget_proxy, this);
        defaultUrl = ctx.getResources().getString(R.string.default_chinanet_url);


        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.DO_NEXT_TEST:
                    //showNextText();
                    break;
                default:
                    update(msg.what);
                }
            }
        };
        DBManager db = new DBManager(ctx);
        ChinaUnicomAccount  account = db.getUnicomAccount();
        db.release();
		if(account == null){
			//  数据库错误
			
		} else {
			username = account.userName;
			password = account.password;
			address = account.address;
		}
		
		webAuthManager = GlobalApp.unicomAuthManager;
		if(webAuthManager == null) {
			webAuthManager = new UnicomWebAuthManager();
		}
        webAuthManager.setHandler(handler);
        wlanManager = new WlanManager(ctx);
        wlanManager.setHandler(handler);
        task = (Task)ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);
        frequency = task.testCount;
 
        start();

        //scanWifi();
    }

    /*
    private void scanWifi() {
        this.showMessageDialog(ctx, "正在扫描附近Wifi热点...");
        new Thread() {
            public void run() {
                wlanManager.startScan();
            }
        }.start();
    }

    private void enableNetWork(final ScanResult scan) {
        this.showMessageDialog(ctx, "正在连接Wifi...");
        new Thread() {
            public void run() {
                wlanManager.connect(scan);
            }
        }.start();

    }*/
    
    private void update(int what) {
    	//----------------------------------------------------------
		if(isFirst) {
			isFirst = false;
			StringBuffer temp = new StringBuffer();
			GlobalApp.result_WEB_test = temp;
		}
	//----------------------------------------------------------
        testedTimes++;
        this.setDialogProgress(testedTimes);
        StringBuffer s = new StringBuffer();
        float costTime = (webAuthManager.getEndTime() - webAuthManager.getStartTime()) / (float)1000;
        if (MessageWhat.LOGIN_SUCCESS == what) {
            s.append("第").append(current).append("次 登录成功，时延：").append(costTime).append('s');
          //----------------------------------------------------------
			
			GlobalApp.result_WEB_test.append("第").append(current)
					.append("次 登录成功，时延：").append(costTime).append("s\n");
		
		//----------------------------------------------------------
            loginTotalTime += costTime;
            lsuccessTimes++;
        } else if (MessageWhat.LOGOUT_SUCCESS == what) {
            s.append("第").append(current).append("次 下线成功，时延：").append(costTime).append('s');
            s.append("第").append(current).append("次 下线成功，时延：").append(costTime).append('s');
            //----------------------------------------------------------
			
				GlobalApp.result_WEB_test.append("第").append(current)
						.append("次 下线成功，时延：").append(costTime).append("s\n");
		
			//----------------------------------------------------------
            logoutTotalTime += costTime;
            osuccessTimes++;
        } else if (what == MessageWhat.LOGIN_FAILED) {
            s.append("第").append(current).append("次 登录失败");
            s.append("第").append(current).append("次 登录失败");
            //---------------------------------------------------------- 
				GlobalApp.result_WEB_test.append("第").append(current).append("次 登录失败\n"); 
			//----------------------------------------------------------
//            showMessage(ctx, "web认证第"+current+"次登录失败");
        } else if (what == MessageWhat.LOGOUT_FAILED) {
            s.append("第").append(current).append("次 下线失败");
          //----------------------------------------------------------
			
			GlobalApp.result_WEB_test.append("第").append(current).append("次 下线失败\n");

		//----------------------------------------------------------
//            showMessage(ctx, "web认证第"+current+"次下线失败"); 
        }
        if (MessageWhat.DONE == what) {
        	DecimalFormat df = new DecimalFormat("#0.000");
            float lavg = (lsuccessTimes == 0) ? 0 : loginTotalTime / (float)lsuccessTimes;
            // long oavg = (osuccessTimes == 0) ? 0 : logoutTotalTime /
            // osuccessTimes;
            float sucessRate = ((float) lsuccessTimes / frequency) * 100;
            float offSuccessRate = ((float) osuccessTimes / frequency) * 100;
            s = new StringBuffer();
            s.append("认证次数：").append(frequency).append("次; ");
            s.append("成功次数：").append(lsuccessTimes).append('次').append('\n');
            s.append("认证平均时延：").append(df.format(lavg)).append('s').append('\n');
            s.append("认证成功率：").append(sucessRate).append('%').append(" 下线成功率：").append(offSuccessRate).append('%');
          //----------------------------------------------------------
			
			GlobalApp.result_WEB_test.append("\n认证次数：").append(frequency).append("次")
					.append("\n成功次数：").append(lsuccessTimes).append("次")
					.append("\n认证平均时延：").append(df.format(lavg)).append("s")
					.append("\n认证成功率：").append(sucessRate).append("%")
					.append("\n下线成功率：").append(offSuccessRate).append("%\n");;

		//----------------------------------------------------------

            task.endTime = StringUtils.getDateTime();
            task.webDelay = String.valueOf(df.format(lavg));
            task.webSuccessRate = String.valueOf(sucessRate);
            task.webOffSuccessRate = String.valueOf(offSuccessRate);
            
            task.webLoginCount = task.testCount + "";
            task.webLoginSuccessCount = lsuccessTimes +"";
            task.webOutCount = task.testCount + "";
            task.webOutSuccessCount = osuccessTimes +"";
            
            ctx.getIntent().putExtra(TAG_REFER_TASK, task);

            dismissProgressDialog();
			lastWebAuth();
        }
        processing = false;
    }

    private void clear() {
        testedTimes = 0;
        current = 0;
        loginTotalTime = 0;
        logoutTotalTime = 0;
        lsuccessTimes = 0;
        osuccessTimes = 0;
        processing = false;
    }

    public void start() {
        /*final String userName = userNameEt.getText().toString();
        final String pwd = pwdEt.getText().toString();
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(pwd)) {
            this.showMessage(ctx, "请输入账号或密码.");
            return;
        }*/
        clear();
        final FTPConfig ftp = this.getFTPConfig(ctx);
        if (ftp != null) {
          //  this.showProgressDialog(ctx, "正在进行WEB认证测试...", frequency * 2); 
            new Thread() {
                public void run() {
                	webAuthManager.logout();
                	executable = true;
                    while (current < frequency && executable) {
                    	/*if(!logouting)
                    	{
                    		logouting = true;
                    		webAuthManager.logout();
                    		try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                Log.e(TAG, "WEB登录认证时线程等待出错：", e);
                            }
                    	}*/
                        if (!processing) {
                            processing = true;
                            webAuthManager.setStartTime(System.currentTimeMillis());
                            current++;
                            boolean success = webAuthManager.auth(defaultUrl, username, password, address);
                            webAuthManager.setEndTime(System.currentTimeMillis());
                            if (success)
                                webAuthManager.sendMsg(MessageWhat.LOGIN_SUCCESS);
                            else {
                                webAuthManager.sendMsg(MessageWhat.LOGIN_FAILED);
                            }

                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                Log.e(TAG, "WEB登录认证时线程等待出错：", e);
                            }
                            webAuthManager.setStartTime(System.currentTimeMillis());
                            //if (success) {
                                success = webAuthManager.logout();
                            //}
                            webAuthManager.setEndTime(System.currentTimeMillis());
                            if (success)
                                webAuthManager.sendMsg(MessageWhat.LOGOUT_SUCCESS);
                            else {
                                webAuthManager.sendMsg(MessageWhat.LOGOUT_FAILED);
                            }

                            if (current == frequency) {
                                webAuthManager.sendMsg(MessageWhat.DONE);
                            }
                        }
                    }
                }
            }.start();
        }
    }

    private void lastWebAuth() {
    	new Thread() {
			public void run() {
				webAuthManager.auth(defaultUrl, username, password, address);
				handlerSendToTarget(handlerChild, MessageWhat.HANDLER_WEB);
			}
    	}.start();
    }
}
